<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 订单的一些通用方法
 *
 * @author      Eden
 * @datetime    2016/12/3 15:38
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Order_Model extends ADM_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @var array
     */
    private $formatStatus = array(
        'Unpaid' => '等待付款',
        'Pending' => '等待发货',
        'Dispatch' => '已发货',
        'Complete' => '已完成',
        'Refund' => '退货',
        'Refunded' => '退货完成',
        'Cancel' => '已取消'
    );

    /**
     * 根据用户ID获取所有订单信息
     * @param $userId
     * @return array|bool
     */
    public function getOrdersByUserId($userId)
    {
        try {
            $userDb = clone($this->db);
            $userDb->where('userId', $userId);
            $userDb->order_by('created', 'desc');
            $query =$userDb->get('user_order');
            $rows = $query->result_array();
            return $this->_getGoods($rows);
        } catch(PDOException $e) {
            return false;
        }
    }

    /**
     * 获取所有订单
     * @param $params
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public function getAll($params, $offset = 0, $limit = 20)
    {
        $where = array();

        // 查询状态
        if (!empty($params['orderStatus'])) {
            $where['uo.status'] = $params['orderStatus'];
        }

        $adminid = adminId();
        if ($adminid == 2) {
            $where['uo.virtual'] = 0;
        }

        try {

            $totalDb = clone($this->db);
            $total = $totalDb->where($where)->from('user_order as uo')->count_all_results();
            if (empty($total)){
                return false;
            }

            $oDb = clone($this->db);
            $query = $oDb->select('uo.id, uo.sn, uo.userId, uo.totalPrice, uo.goodsPrice, uo.expressPrice, 
                uo.integralPrice, uo.voucherPrice,
                uo.payMode, uo.created, uo.payWay, uo.status, u.nickName')
                ->from('user_order uo')
                ->join('user as u', 'u.id = uo.userId')
                ->limit($limit, $offset)
                ->order_by('uo.created', 'DESC')
                ->where($where)
                ->get();
            $result = $query->result_array();
            $orderIds = array();
            if (is_array($result) && !empty($result)) foreach ($result as &$res) {
                $res['formatStatus'] = $this->formatStatus[$res['status']];
                $res['totalPrice'] = money_format("%i", $res['totalPrice'] / 100);
                $res['goodsPrice'] = money_format("%i", $res['goodsPrice'] / 100);
                $res['expressPrice'] = money_format("%i", $res['expressPrice'] / 100);
                array_push($orderIds, $res['id']);
            }

            $express = $this->_getExpress($orderIds);
            $this->_afterExpress($result, $express);

            return array(
                'total' => intval($total),
                'data' => $result,
                'nextPage' => ($offset + $limit) < $total
            );
        } catch(PDOException $e) {
            return false;
        }
    }

    /**
     * 格式化数据
     * @param $result
     * @param $exps
     */
    private function _afterExpress(&$result, $exps)
    {
        foreach($result as &$item) {
            $exp = value($exps, $item['id'], array());
            $item['expressNo'] = value($exp, 'expressNo', '');
            $item['expressName'] = value($exp, 'expressName', '');
            $item['expressSimpleName'] = value($exp, 'simpleName', '');
            $item['expressTime'] = value($exp, 'created', '');
        }
    }

    /**
     * 获取物流
     * @param $orderIds
     * @return array
     */
    private function _getExpress($orderIds)
    {
        $result = array();
        if (!empty($orderIds)) {
            $eDb = clone($this->db);
            $query = $eDb->where_in('orderId', $orderIds)
                ->select('orderId, expressNo, expressName, simpleName, created')
                ->get('user_order_express');
            $rows = $query->result_array();
            if (!empty($rows)) foreach($rows as $row) {
                $result[$row['orderId']] = $row;
            }
        }
        return $result;
    }

    /**
     * 获取订单中的产品
     * @param array $orders
     * @return array|bool
     */
    private function _getGoods($orders = array())
    {

        if (empty($orders)) {
            return false;
        }

        $this->load->helper('timer');

        $orderGoods = array();
        if (!empty($orders) && is_array($orders)) foreach ($orders as &$order) {
            // 收集每一笔订单的商品
            $orderResult = array();
            $orderId = $order['id'];
            $this->db->select('sg.goodsName, sg.status, sg.thumb, uog.num, uog.goodsId, uog.price');
            $this->db->where('orderId', $orderId);
            $this->db->join('base_goods as sg', 'sg.id = uog.goodsId');
            $query = $this->db->get('user_order_goods as uog');
            $result = $query->result_array();

            if (!empty($result)) foreach($result as &$item) {
                $item['thumb'] = thumb($item['thumb'], 100, 100);
            }

            $orderGoods[$orderId] = $result;

            $orderResult['orderId'] = intval($order['id']);
            $orderResult['sn'] = value($order, 'sn');
            $orderResult['totalPrice'] = money_format('%i', value($order, 'totalPrice') / 100);
            $orderResult['goodsPrice'] = money_format('%i', value($order, 'goodsPrice') / 100);
            $orderResult['expressPrice'] = money_format('%i', value($order, 'expressPrice') / 100);
            $orderResult['addressId'] = intval($order['addressId']);
            $orderResult['created'] = formateTimeStamp($order['created']);
            $orderResult['payWay'] = intval($order['payWay']);
            $orderResult['status'] = $order['status'];
            $orderResult['formatStatus'] = $this->formatStatus[$order['status']];
            $orderResult['goods'] = $result;

            $order = $orderResult;
        }

        return $orders;
    }

    /**
     * 最新订单
     * @param int $limit
     * @return mixed
     */
    public function getLatestOrders($limit = 10)
    {
        $adminid = adminId();
        if ($adminid == 2) {
            $query = $this->db
                ->select('o.id, o.sn, u.nickName, o.totalPrice, o.created, o.status')
                ->from('user_order as o')
                ->where('o.virtual', 0)
                ->join('user as u', 'u.id = o.userId')
                ->limit($limit)
                ->order_by('o.created DESC')
                ->get();
        } else {
            $query = $this->db
                ->select('o.id, o.sn, u.nickName, o.totalPrice, o.created, o.status')
                ->from('user_order as o')
                ->join('user as u', 'u.id = o.userId')
                ->limit($limit)
                ->order_by('o.created DESC')
                ->get();
        }
        $order = $query->result_array();
        if ($order) foreach($order as &$item) {
            $item['formatStatus'] = $this->formatStatus[$item['status']];
            $item['totalPrice'] = money_format('%i', $item['totalPrice'] / 100);
        }
        return $order;
    }
}
